package cn.javacart.jopencart.controller.catalog.module;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import php.runtime.memory.support.MemoryUtils;
import cn.javacart.jfinal.php.render.PhpRender;
import cn.javacart.jopencart.controller.JOpencartController;
import cn.javacart.jopencart.controller.JOpencartModule;
import cn.javacart.jopencart.library.SessionConfigService;
import cn.javacart.jopencart.model.Product;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfplugin.kit.mockrender.MockRenderKit;

/**
 * 推荐商品
 * @author farmer
 *
 */
public class ModuleFeaturedModule extends JOpencartModule{

	private String extra = null;
	
	public ModuleFeaturedModule(JOpencartController controller) {
		super(controller);
	}
	
	public ModuleFeaturedModule(JOpencartController controller,Object extra) {
		super(controller);
		this.extra = (String) extra;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String render() {
		language.load("/catalog/language/{0}/module/featured.php");
		dataMap.put("heading_title", language.get("heading_title"));
		dataMap.put("text_tax", language.get("text_tax"));
		dataMap.put("button_cart", language.get("button_cart"));
		dataMap.put("button_wishlist", language.get("button_wishlist"));
		dataMap.put("button_compare", language.get("button_compare"));
		HashMap<String,Object> settingMap = JSON.parseObject(extra, HashMap.class);
		int limit = 4;
		if(StrKit.notBlank((String)settingMap.get("limit"))){
			limit = Integer.parseInt((String)settingMap.get("limit"));
		}
		List<Map<String, Object>> productList = new ArrayList<Map<String,Object>>();
		List<Object> products = (List<Object>) settingMap.get("product");
		int size = products.size();
		for (int i = 0; i < (limit>size?size:limit); i++) {
			Product p = Product.ME.findFirst("SELECT\n" + 
					"	DISTINCT *,\n" + 
					"	pd.name AS name,\n" + 
					"	p.image,\n" + 
					"	m.name AS manufacturer,\n" + 
					"	if(\n" + 
					"		(\n" + 
					"			select\n" + 
					"				SUM( op.quantity ) AS order_count\n" + 
					"			FROM\n" + 
					"				joc_order_product op\n" + 
					"			where\n" + 
					"				op.product_id = p.product_id\n" + 
					"		),\n" + 
					"		null,\n" + 
					"		0\n" + 
					"	) as order_count,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			price\n" + 
					"		FROM\n" + 
					"			joc_product_discount pd2\n" + 
					"		WHERE\n" + 
					"			pd2.product_id = p.product_id\n" + 
					"			AND pd2.customer_group_id = ?\n" + 
					"			AND pd2.quantity = '1'\n" + 
					"			AND(\n" + 
					"				(\n" + 
					"					pd2.date_start = '0000-00-00'\n" + 
					"					OR pd2.date_start < NOW()\n" + 
					"				)\n" + 
					"				AND(\n" + 
					"					pd2.date_end = '0000-00-00'\n" + 
					"					OR pd2.date_end > NOW()\n" + 
					"				)\n" + 
					"			)\n" + 
					"		ORDER BY\n" + 
					"			pd2.priority ASC,\n" + 
					"			pd2.price ASC LIMIT 1\n" + 
					"	) AS discount,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			price\n" + 
					"		FROM\n" + 
					"			joc_product_special ps\n" + 
					"		WHERE\n" + 
					"			ps.product_id = p.product_id\n" + 
					"			AND ps.customer_group_id = ?\n" + 
					"			AND(\n" + 
					"				(\n" + 
					"					ps.date_start = '0000-00-00'\n" + 
					"					OR ps.date_start < NOW()\n" + 
					"				)\n" + 
					"				AND(\n" + 
					"					ps.date_end = '0000-00-00'\n" + 
					"					OR ps.date_end > NOW()\n" + 
					"				)\n" + 
					"			)\n" + 
					"		ORDER BY\n" + 
					"			ps.priority ASC,\n" + 
					"			ps.price ASC LIMIT 1\n" + 
					"	) AS special,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			points\n" + 
					"		FROM\n" + 
					"			joc_product_reward pr\n" + 
					"		WHERE\n" + 
					"			pr.product_id = p.product_id\n" + 
					"			AND customer_group_id = ?\n" + 
					"	) AS reward,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			ss.name\n" + 
					"		FROM\n" + 
					"			joc_stock_status ss\n" + 
					"		WHERE\n" + 
					"			ss.stock_status_id = p.stock_status_id\n" + 
					"			AND ss.language_id = ?\n" + 
					"	) AS stock_status,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			wcd.unit\n" + 
					"		FROM\n" + 
					"			joc_weight_class_description wcd\n" + 
					"		WHERE\n" + 
					"			p.weight_class_id = wcd.weight_class_id\n" + 
					"			AND wcd.language_id = ?\n" + 
					"	) AS weight_class,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			lcd.unit\n" + 
					"		FROM\n" + 
					"			joc_length_class_description lcd\n" + 
					"		WHERE\n" + 
					"			p.length_class_id = lcd.length_class_id\n" + 
					"			AND lcd.language_id = ?\n" + 
					"	) AS length_class,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			AVG( rating ) AS total\n" + 
					"		FROM\n" + 
					"			joc_review r1\n" + 
					"		WHERE\n" + 
					"			r1.product_id = p.product_id\n" + 
					"			AND r1.status = '1'\n" + 
					"		GROUP BY\n" + 
					"			r1.product_id\n" + 
					"	) AS rating,\n" + 
					"	(\n" + 
					"		SELECT\n" + 
					"			COUNT(*) AS total\n" + 
					"		FROM\n" + 
					"			joc_review r2\n" + 
					"		WHERE\n" + 
					"			r2.product_id = p.product_id\n" + 
					"			AND r2.status = '1'\n" + 
					"		GROUP BY\n" + 
					"			r2.product_id\n" + 
					"	) AS reviews,\n" + 
					"	p.sort_order\n" + 
					"FROM\n" + 
					"	joc_product p\n" + 
					"LEFT JOIN joc_product_description pd ON\n" + 
					"	(\n" + 
					"		p.product_id = pd.product_id\n" + 
					"	)\n" + 
					"LEFT JOIN joc_product_to_store p2s ON\n" + 
					"	(\n" + 
					"		p.product_id = p2s.product_id\n" + 
					"	)\n" + 
					"LEFT JOIN joc_manufacturer m ON\n" + 
					"	(\n" + 
					"		p.manufacturer_id = m.manufacturer_id\n" + 
					"	)\n" + 
					"WHERE\n" + 
					"	p.product_id = ?\n" + 
					"	AND pd.language_id = ?\n" + 
					"	AND p.status = '1'\n" + 
					"	AND p.date_available <= NOW()\n" + 
					"	AND p2s.store_id = ?", 
					1,
					1,
					1,
					SessionConfigService.get("config_language_id"),
					SessionConfigService.get("config_language_id"),
					SessionConfigService.get("config_language_id"),
					products.get(i),
					SessionConfigService.get("config_language_id"),
					0);
			Map<String, Object> productMap = new HashMap<String, Object>();			
			productMap.put("price", "$"+(p.getBigDecimal("discount") != null ? p.getBigDecimal("discount").toString():p.getBigDecimal("price").toString()));
			Document parse = Jsoup.parse(StringEscapeUtils.unescapeHtml4(p.getStr("description")));
			productMap.put("description", parse.text().substring(0, 100));
			String uri = p.getStr("image");
			productMap.put("thumb", uri.substring(0, uri.lastIndexOf("."))+"_"+settingMap.get("width")+"x"+settingMap.get("height")+uri.substring(uri.lastIndexOf("."),uri.length()));
			productMap.put("name", p.getStr("name"));
			productMap.put("href", url.link("product/product", "product_id="+p.get("product_id")));
			productList.add(productMap);
		}
		dataMap.put("products", MemoryUtils.valueOf(productList));
		return MockRenderKit.render(new PhpRender("/catalog/view/theme/default/template/module/featured.tpl", dataMap));
	}

}
